﻿using Models;
using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows.Input;

namespace MainClient2.ViewModels
{
    public class LoginViewModel : BindableBase
    {
        public string UserName { get; set; }

        public string Password { get; set; }

        public User User { get; set; }

        //[DependsOn("Radius")]  [DoNotNotify] [DependsOn("GivenName","FamilyName")]
        //public string FullName => $"{GivenNames} {FamilyName}"; [AlsoNotifyFor("FullName")]

        public ICommand LoginCommand
        {
            get
            {
                return new RelayCommand((para) =>
                {
                    using (webyym.MainService mainService = new webyym.MainService())
                    {
                        //string res1 = mainService.CommonInterface((new Request() { Header = RequestHeader.Login, Data = new User() { UserName = this.UserName, Password = this.Password } }).ToJsonString());
                        Response<User> response1 = RequestWebService<User>(new Request() { Header = RequestHeader.Login, Data = new User() { UserName = this.UserName, Password = this.Password } });


                        // todo 应该遍历权限
                        foreach (string item in new string[] { "UserManage.exe" })
                        {
                            string path = System.AppDomain.CurrentDomain.BaseDirectory + item;
                            FileInfo fileInfo = new FileInfo(path);
                            if (!fileInfo.Exists)
                                return;// new Response<byte[]>() { Success = false, Message = $"服务器上不存在此文件:{CurrentUploadFilePath}" }.ToJsonString();// todo 错误要等级 要解决方案，要描述

                            Assembly assembly = Assembly.LoadFile(path);
                            if (assembly == null)
                                return;// new Response<byte[]>() { Success = false, Message = $"服务器上不存在此文件:{CurrentUploadFilePath}" }.ToJsonString();// todo 错误要等级 要解决方案，要描述


                            AssemblyName assemblyName = assembly.GetName();
                            string localversion = assemblyName.Version.ToString();

                            string res = mainService.CheckUpdate(item, localversion);// 返回值不对   item, fileInfo.DirectoryName
                            Response<byte[]> response = JsonConvert.DeserializeObject<Response<byte[]>>(res);
                            try
                            {

                                byte[] bytes = response.Data;
                                if (bytes != null && bytes.Length > 1)
                                {
                                    //if (!Directory.Exists(item))
                                    //{
                                    //    Directory.CreateDirectory(item);
                                    //}
                                    if (!File.Exists(item))
                                    {
                                        File.Create(item).Dispose();
                                    }
                                    //如果不存在完整的上传路径就创建
                                    FileInfo downloadInfo = new FileInfo(item);
                                    if (downloadInfo.IsReadOnly) { downloadInfo.IsReadOnly = false; }
                                    //定义并实例化一个内存流，以存放提交上来的字节数组。
                                    MemoryStream ms = new MemoryStream(bytes);
                                    //定义实际文件对象，保存上载的文件。
                                    FileStream fs = new FileStream(item, FileMode.Create);
                                    ///把内内存里的数据写入物理文件
                                    ms.WriteTo(fs);
                                    fs.Flush();
                                    ms.Flush();
                                    ms.Close();
                                    fs.Close();
                                    fs = null;
                                    ms = null;
                                }
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    //if (user != null)
                    //{
                    //    UnityRoot.container.RegisterInstance<User>(new User() { UserName = this.UserName });
                    //}
                });
            }
        }

        public Response RequestWebService(Request request)
        {
            using (webyym.MainService mainService = new webyym.MainService())
            {
                string re = request.ToJsonString();
                string res = mainService.CommonInterface(re);
                return JsonConvert.DeserializeObject<Response>(res);
            }
        }

        public Response<T> RequestWebService<T>(Request request)
        {
            using (webyym.MainService mainService = new webyym.MainService())
            {
                string re = request.ToJsonString();
                string res = mainService.CommonInterface(re);
                return JsonConvert.DeserializeObject<Response<T>>(res);
            }
        }
    }
}
